package cn.edu.zjgsu.ito.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPTableEvent;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class StudentExportPdfService implements PdfPTableEvent {

	//自定义中文字体位置
	String imgPdf = "";
	String imgPdf2 = "";
	String imgPdf3 = "";
	String fontPdf = "";
	String fontPdf2 = "";
	String fontPdf3 = "";

	public void createPdf(OutputStream out,String passportNo){
		//		String projectPath = this.getClass().getResource("/").getPath().substring(1,10);
		String path = this.getClass().getResource("/").getPath();

		try {
			imgPdf = URLDecoder.decode(path,"UTF-8").replace("WEB-INF/classes/", "img/newlogo.png").substring(1);
			imgPdf2 = URLDecoder.decode(path,"UTF-8").replace("WEB-INF/classes/", "img/downfont.png").substring(1);
			
			fontPdf = URLDecoder.decode(path,"UTF-8").replace("WEB-INF/classes/", "fonts/TIMES.TTF").substring(1);
			fontPdf2 = URLDecoder.decode(path,"UTF-8").replace("WEB-INF/classes/", "fonts/TIMESBD.TTF").substring(1);
			fontPdf3 = URLDecoder.decode(path,"UTF-8").replace("WEB-INF/classes/", "fonts/SIMHEI.TTF").substring(1);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try{
			// step 1
			//			 Document document = new Document(new RectangleReadOnly(595F,842F));
			Document document = new Document(PageSize.A4);
			// step 2
			PdfWriter.getInstance(document,out);
			//设计字体
			//			 bfHei = BaseFont.createFont("STSong-Light", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			//			 BaseFont bf = BaseFont.createFont(fontPath,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			//			bfHei = BaseFont.createFont(fontPdf,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
			BaseFont bfHei = BaseFont.createFont(fontPdf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			BaseFont bfHei2 = BaseFont.createFont(fontPdf2, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			Font font = new Font(bfHei,21/2);
			Font font2 = new Font(bfHei2,21/2);
			//			 Font font1 = new Font(bfHei,12);
			Image image = Image.getInstance(imgPdf);
			Image image2 = Image.getInstance(imgPdf2);
			image.scaleAbsolute(350,200);
			image2.scaleAbsolute(380,35);
			image.setAlignment(Element.ALIGN_CENTER);
			image2.setAlignment(Element.ALIGN_CENTER);

			Record stu = Db.findFirst("select * from student_info where passportNo=?",passportNo);
			String name = stu.getStr("firstName") + " " + stu.getStr("lastName");
			String sNo = stu.getStr("sNo");
			String years = stu.getStr("eduStartDate") +"-"+ (Integer.valueOf(stu.getStr("eduStartDate")) + 4);
			// step 3
			Paragraph oneLine = new Paragraph();
			document.open();

			Chunk oneLine1 = new Chunk("This is to certify that ",font);  
			Chunk oneLine2 = new Chunk(name,font2);
			oneLine.add(oneLine1);
			oneLine.add(oneLine2);
			document.add(image); 
			document.add(image2); 
			document.add(new Paragraph("   "));
			document.add(oneLine);
			//处理学生学期
			Paragraph twoLine = new Paragraph();
			Chunk twoLine1 = new Chunk("Attended the University in the years ",font);  
			Chunk twoLine2 = new Chunk(years,font2);
			twoLine.add(twoLine1);
			twoLine.add(twoLine2);
			document.add(twoLine);
			document.add(new Paragraph("   "));
			document.add(new Paragraph("Student Name:" + name,font2));
			document.add(new Paragraph("Student ID:"+ sNo,font2));

			document.add(new Paragraph("   "));
			document.add(gradeTitle());
			document.add(new Paragraph("———————————————————————————————————————————"));
			List<Record> term = Db.find("select * from student_grade where passportNo=? group by termValue",passportNo);
			for(int i = 0;i < term.size();i++){
				//对学期进行处理
				String termValue1 = term.get(i).getStr("termValue");
				String termValue = "";
				String temp1 = termValue1.substring(0,4);
				String temp2 = termValue1.substring(5,9);
				String temp3 = termValue1.substring(10,11);
				if(temp3.equals("1")){
					termValue = temp1 + "-" + temp2 + "(First Semester)";
				}if(temp3.equals("2")){
					termValue = temp1 + "-" + temp2 + "(Second Semester)";
				}
				document.add(new Paragraph("Academic Year:" + termValue,font2));
				document.add(new Paragraph("   "));
				document.add(gradePrint(passportNo,termValue1));
				document.add(new Paragraph("   "));

			}
			document.add(new Paragraph("———————————————————————————————————————————"));

			document.add(new Paragraph("GRADING SYSTEM                                                                                                This official document is bona fide when",font));
			document.add(new Paragraph("                                                                                                                                   mprinted with the institutional seal in the",font));
			document.add(new Paragraph("A-4.0  B-3.0  C-2.0  P-1.0  F-0.0                                                                             section to the left. This document may not",font));
			document.add(new Paragraph("                                                                                                                                   be relevant to a third party without written",font));
			document.add(new Paragraph("                                                                                                                                   consent of the student.",font));
			
//			table.setSplitLate(false);单元格跨页？
//			table.setSplitRows(true);
			
			
			// step 4
			document.close();
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}



	//学生成绩
	public List<Record> stuGrades(String passportNo,String termValue){
		System.out.println("-----------3---------");
		List<Record> stu = Db.find("select * from student_grade,course,test where student_grade.courseNo=course.courseNo and student_grade.testNo=test.testNo and test.testLock='1' and student_grade.passportNo=? and student_grade.termValue=?",passportNo,termValue);
		String gradeLevel = "";
		for(int i = 0;i < stu.size();i++){
//			String finalGrade = "";
//			if(stu.get(i).getStr("finalGrade") == null){
//				finalGrade = stu.get(i).getStr("grade");
//			}else{
//				finalGrade = stu.get(i).getStr("finalGrade");
//			}
			String grade = stu.get(i).getStr("grade");
//
			if(grade.equals("作弊") || grade.equals("旷考")){
				gradeLevel = "F";
				stu.get(i).set("grade","0");
				stu.get(i).set("gradeLevel",gradeLevel);
			}else if(grade.equals("A") || grade.equals("B") || grade.equals("C") || grade.equals("P") || grade.equals("F")){
				gradeLevel = grade;
				stu.get(i).set("gradeLevel",gradeLevel);
			}else {
				int gradeTemp = Integer.valueOf(grade);
				if(gradeTemp >= 90){
					gradeLevel = "A";
				}else if(gradeTemp >= 80){
					gradeLevel = "B";
				}else if(gradeTemp >= 70){
					gradeLevel = "C";
				}else if(gradeTemp >= 60){
					gradeLevel = "P";
				}else if(gradeTemp < 90){
					gradeLevel = "F";
				}
				stu.get(i).set("gradeLevel",gradeLevel);
			}
		}
		return stu;
	}

	//成绩输出
	public PdfPTable gradePrint (String passportNo,String termValue){

		try {
			PdfPTable table = new PdfPTable(6);

			BaseFont bfHei = BaseFont.createFont(fontPdf2,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			BaseFont bfHeiChine = BaseFont.createFont(fontPdf3,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);

			Font font = new Font(bfHei,9);
			table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中   
			table.setHorizontalAlignment(Element.ALIGN_MIDDLE);//垂直居中   

			Font fontChina = new Font(bfHeiChine,9);

			table.setTotalWidth(new float[]{58,210,52,94,50,53});
			table.setLockedWidth(true);

			List<Record> stuGrade = stuGrades(passportNo,termValue);
			PdfPCell cell;



			for(int i = 0;i < stuGrade.size();i++){
				cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("courseNo"),font));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
//				cell.setBorderWidth(5f);
//				cell.setBorderColor(BaseColor.WHITE);
				cell.setBorderWidth(0);
				table.addCell(cell);

				cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("courseName"),font));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
//				cell.setBorderColor(BaseColor.WHITE);
				cell.setBorderWidth(0);
				table.addCell(cell);

				cell = new PdfPCell(new Phrase(stuGrade.get(i).getInt("credit").toString(),font));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
//				cell.setBorderColor(BaseColor.WHITE);
				cell.setBorderWidth(0);
				table.addCell(cell);

				String testType = "";
				String testTypeTemp = stuGrade.get(i).getStr("testType");
				if(testTypeTemp.equals("1")){
					testType = "1";
				}else if(testTypeTemp.equals("2")){
					testType = "0";
				}
				cell = new PdfPCell(new Phrase(testType,font));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
//				cell.setBorderColor(BaseColor.WHITE);
				cell.setBorderWidth(0);
				table.addCell(cell);

				/*if(stuGrade.get(i).getStr("grade").equals("旷考") || stuGrade.get(i).getStr("grade").equals("作弊")){//处理补考成绩
					System.out.println("进入到这里面。");
					cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("grade"),fontChina));
				}else{
					cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("grade"),font));
				}
				
				if(stuGrade.get(i).getStr("grade").equals("旷考") || stuGrade.get(i).getStr("grade").equals("作弊")){
					System.out.println("进入到这里面。");
					cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("0"),font));
				}else{
					cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("grade"),font));
				}*/
				cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("grade"),font));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
//				cell.setBorderColor(BaseColor.WHITE);
				cell.setBorderWidth(0);
				table.addCell(cell);
				/*if(stuGrade.get(i).getStr("gradeLevel").equals("旷考") || stuGrade.get(i).getStr("gradeLevel").equals("作弊")){
					cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("gradeLevel"),fontChina));
				}else{
					cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("gradeLevel"),font));
				}*/
				cell = new PdfPCell(new Phrase(stuGrade.get(i).getStr("gradeLevel"),font));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
//				cell.setBorderColor(BaseColor.WHITE);
				cell.setBorderWidth(0);
				table.setSplitRows(true);
				table.addCell(cell);
			}
			return table;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}


	//打印标题
	public PdfPTable gradeTitle(){
		try {
			PdfPTable table = new PdfPTable(6);
			BaseFont bfHei;

			
			
			bfHei = BaseFont.createFont(fontPdf2,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);

			Font font = new Font(bfHei,9);
			table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中   
			table.setHorizontalAlignment(Element.ALIGN_MIDDLE);//垂直居中   
			table.setTotalWidth(new float[]{58,210,52,94,50,53});
			table.setLockedWidth(true);
			PdfPCell cell;
			table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
			
			cell = new PdfPCell(new Phrase("Unit Code",font));
			
//			cell = new PdfPCell(new Paragraph("Unit Code",font));
//			table.addCell(new Paragraph("Unit Code",font)); 
			
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
//			cell.setBorderColor(BaseColor.WHITE);
			cell.setBorderWidth(0);
			table.addCell(cell);
			
			cell = new PdfPCell(new Phrase("Unit Title",font));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
//			cell.setBorderColor(BaseColor.WHITE);
			cell.setBorderWidth(0);
			table.addCell(cell);

			cell = new PdfPCell(new Phrase("Credits",font));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
//			cell.setBorderColor(BaseColor.WHITE);
			cell.setBorderWidth(0);
			table.addCell(cell);

			cell = new PdfPCell(new Phrase("AwardedAttempt",font));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
//			cell.setBorderColor(BaseColor.WHITE);
			cell.setBorderWidth(0);
			table.addCell(cell);

			cell = new PdfPCell(new Phrase("Mark (%)",font));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
//			cell.setBorderColor(BaseColor.WHITE);
			cell.setBorderWidth(0);
			table.addCell(cell);

			cell = new PdfPCell(new Phrase("Outcome",font));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
//			cell.setBorderColor(BaseColor.WHITE);
			cell.setBorderWidth(0);
			table.addCell(cell);
			return table;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	 /** 
	    * 给pdf文件添加水印 
	    * @param InPdfFile 要加水印的原pdf文件路径 
	    * @param outPdfFile 加了水印后要输出的路径 
	    * @param markImagePath 水印图片路径 
	    * @param pageSize 原pdf文件的总页数（该方法是我当初将数据导入excel中然后再转换成pdf所以我这里的值是用excel的行数计算出来的，如果不是我这种可以 直接用reader.getNumberOfPages()获取pdf的总页数） 
	    * @throws Exception 
	    */  
	 public static void addPdfMark(String InPdfFile, String outPdfFile, String markImagePath) throws Exception {  
	      
		    PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());  
		       
		    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));  
		     
		    Image img = Image.getInstance(markImagePath);// 插入水印     
		   
		    img.setAbsolutePosition(25, 100);  
		      
		    int pageSize = reader.getNumberOfPages();
		    
		    for(int i = 1; i <= pageSize; i++) {  
		       
		     PdfContentByte under = stamp.getUnderContent(i);  
		      
		     under.addImage(img);  
		         
		    }  
		      
		    stamp.close();// 关闭   
		    
//		    File tempfile = new File(InPdfFile);  
//		      
//		    if(tempfile.exists()) {  
//		       
//		     tempfile.delete();  
//		    }  
		      
		   }  
	

	@Override
	public void tableLayout(PdfPTable arg0, float[][] arg1, float[] arg2,
			int arg3, int arg4, PdfContentByte[] arg5) {
		// TODO Auto-generated method stub

	}



	public void addWater(String outpath,String newOutPath) {
		// TODO Auto-generated method stub
		
		String path = this.getClass().getResource("/").getPath();
		try {
			imgPdf3 = URLDecoder.decode(path,"UTF-8").replace("WEB-INF/classes/", "img/watermark.png").substring(1);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			addPdfMark(outpath,newOutPath,imgPdf3);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}



}
